package com.creditease.rss.ui;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.creditease.rss.dao.RssDB;
import com.creditease.rss.dao.RssItemDB;
import com.creditease.rss.model.RssItemModel;
import com.creditease.rss.model.RssModel;
import com.creditease.rss.services.FeedServices;
import com.creditease.rss.ui.adapter.RssItemAdapter;
import com.creditease.rss.util.CacheMgr;
import com.creditease.rss.util.ExceptionUtil;
import com.creditease.rss.util.LogUtil;
import com.creditease.rss.util.NetUtil;

public class ListRssActivity extends Activity {

	private final static String TAG = ListRssActivity.class.getName();
	private ListView listView;
	private ImageView titleView;
	private ImageView reflushView;
	private ProgressDialog progressDialog;
	private Animation animation;
	private String url;
	private String link;
	private String sectionId;
	private ProgressBar progressBar;
	private TextView titleText;
	private FeedServices feedServices;
	private RssItemDB db;
	private RssItemAdapter adapter;
	private String title;
	private int pageSize = 20;
	private int index = 0;
	private int totalPage = 0;
	private int currentPage = 0;
	private List<RssItemModel> rssList;
	private View loadMoreView;
	private Button loadMoreButton;
	private int rssCount;
	private static final int MSG_SUCCESS = 0;//
	private static final int MSG_FAILURE = 1;//
	private static final int MSG_LOAD = 2;//
	private static final int DATA_MEPTY = 3;//

	private Handler handler;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.list_rss);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);

		// 设置Home图标
		titleView = (ImageView) findViewById(R.id.titleIcon);
		Drawable drawable = getResources().getDrawable(R.drawable.icon_home);
		titleView.setImageDrawable(drawable);
		titleView.setAdjustViewBounds(true);
		titleView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				ListRssActivity.this.onBackPressed();
			}
		});
		reflushView = (ImageView) findViewById(R.id.reflushIcon);
		reflushView.setAdjustViewBounds(true);
		progressBar = (ProgressBar) findViewById(R.id.progressbar);
		// progressBar.setVisibility(View.VISIBLE);
		// 给刷新按钮 添加刷新事件
		reflushView.setOnClickListener(new ReflushClickListener());
		listView = (ListView) findViewById(R.id.listView);

		// 获取前一页面参数：分类Id
		Intent intent = getIntent();
		sectionId = intent.getExtras().getString("id");

		// 当前页的标题
		title = intent.getExtras().getString("title");
		titleText = (TextView) findViewById(R.id.titleText);
		titleText.setText(title);
		db = new RssItemDB(getApplicationContext());

		rssCount = db.countBySectionId(sectionId);
		if (rssCount % pageSize == 0) {
			totalPage = rssCount / pageSize;
		} else {
			totalPage = rssCount / pageSize + 1;
		}
		Log.d(TAG, "size=" + rssCount + ",totalPage=" + totalPage);
		feedServices = new FeedServices(getApplicationContext());
		loadMoreView = getLayoutInflater().inflate(R.layout.list_loadingmore, null);
		loadMoreButton = (Button) loadMoreView.findViewById(R.id.moreRssBtn);
		rssList = loadData(0);
		adapter = new RssItemAdapter(getApplicationContext(), rssList);
		// 需要放在 setAdapter之前，否则不显示
		if (totalPage > 1) {
			listView.addFooterView(loadMoreView);
		}
		if (rssList.isEmpty()) {
			// View emptyView= getLayoutInflater().inflate(R.layout.list_empty,
			// null);
			listView.setEmptyView(findViewById(R.id.rssEmptyMsg));
		}
		listView.setAdapter(adapter);
		loadMoreButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				loadMoreButton.setText(R.string.loadingMsg); // 设置按钮文字
				handler.post(new Runnable() {
					@Override
					public void run() {
						List<RssItemModel> list2 = loadData(null);
						rssList.addAll(list2);
						adapter.notifyDataSetChanged();
						loadMoreButton.setText(R.string.moreRss); // 恢复按钮文字
						Toast.makeText(getApplicationContext(), "加载成功", Toast.LENGTH_SHORT).show();
					}
				});
			}
		});

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MSG_SUCCESS:
					rssCount = db.countBySectionId(sectionId);
					Log.d(TAG, "size=" + rssCount);

					if (rssCount % pageSize == 0) {
						totalPage = rssCount / pageSize;
					} else {
						totalPage = rssCount / pageSize + 1;
					}

					Log.d(TAG, "size=" + rssCount + ",totalPage=" + totalPage);
					currentPage = 0;
					List<RssItemModel> list = loadData(0);
					rssList.clear();
					rssList.addAll(list);
					adapter.notifyDataSetChanged();
					progressBar.setVisibility(View.INVISIBLE);
					Toast.makeText(getApplicationContext(), "刷新成功", Toast.LENGTH_SHORT).show();
					break;
				case DATA_MEPTY:
					progressBar.setVisibility(View.INVISIBLE);
					Toast.makeText(	getApplicationContext(),
									R.string.rssEmptyMsg,
									Toast.LENGTH_SHORT).show();
					break;
				default:
					progressBar.setVisibility(View.INVISIBLE);
					Toast.makeText(getApplicationContext(), R.string.neterr, Toast.LENGTH_SHORT)
							.show();
					break;
				}
			}
		};
		// 打开详细页面
		listView.setOnItemClickListener(new RssItemClickListener());
	}

	private List<RssItemModel> loadData(Integer start) {
		currentPage++;
		if (start == null) {
			index = index + pageSize;
		} else {
			index = start;
		}
		int loadCount = 0;
		// 当前页大于总页数
		if (currentPage >= totalPage) {
			loadCount = rssCount - (currentPage - 1) * pageSize;
			listView.removeFooterView(loadMoreView);
			Toast.makeText(this, "数据全部加载完!", Toast.LENGTH_SHORT).show();
		}else {
			loadCount=pageSize;
		}
		Log.d(TAG, "currentPage=" + currentPage + ",index=" + index + ",pageSize=" + pageSize);
		List<RssItemModel> items = db.findByPart(sectionId, index, loadCount);
		
		if(CacheMgr.get(sectionId)==null){
			CacheMgr.put(sectionId, items);
		}else {
			List<RssItemModel> list=CacheMgr.get(sectionId);
			list.addAll(items);
		}

		return items;
	}

	private final class RssItemClickListener implements OnItemClickListener {

		/**
		 * Description:
		 * 
		 * @param
		 * @throws
		 * @Author liong Create Date: 2012-3-15 下午3:16:25
		 */
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

			RssItemModel item = (RssItemModel) parent.getItemAtPosition(position);
			Intent intent = new Intent();
			intent.setClass(ListRssActivity.this, RssReader.class);
			intent.putExtra("title", title);
			intent.putExtra("id", item.id);
			intent.putExtra("url", url);
			intent.putExtra("link", link);
			intent.putExtra("sectionId", sectionId);

			if (!item.isRead) {
				item.isRead = true;
				// 更新为已读
				db.update(item);
			}
			startActivity(intent);
		}

	}

	private final class ReflushClickListener implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			progressBar.setVisibility(View.VISIBLE);
			if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
				handler.obtainMessage(MSG_FAILURE).sendToTarget();
				return;
			}
			Runnable r = new Runnable() {
				@Override
				public void run() {
					try {
						// 刷新
						feedServices.refrush(sectionId);
						rssCount = db.countBySectionId(sectionId);
						if (rssCount > 0) {
							handler.obtainMessage(MSG_SUCCESS).sendToTarget();
						} else {
							handler.obtainMessage(DATA_MEPTY).sendToTarget();
						}
					}
					catch (Exception e) {
						e.printStackTrace();
						String msg = ExceptionUtil.exception2String(e);
						LogUtil.d(msg);
						handler.obtainMessage(MSG_FAILURE).sendToTarget();
					}
				}
			};
			Thread thread = new Thread(r);
			thread.start();

		}
	}
}